package br.unb.midialab.pianogame.midi;

import java.util.ArrayList;
import java.util.List;

import javax.sound.midi.MidiDevice;
import javax.sound.midi.MidiSystem;
import javax.sound.midi.MidiUnavailableException;
import javax.sound.midi.Receiver;
import javax.sound.midi.Sequencer;
import javax.sound.midi.Synthesizer;
import javax.sound.midi.Transmitter;

import br.unb.midialab.pianogame.main.JogoPiano;

public class MidiHandler {
	private static ArrayList<Receiver> listeners;

	public MidiHandler(Receiver parent) {

		MidiDevice device;
		MidiDevice.Info[] infos = MidiSystem.getMidiDeviceInfo();
		for (int i = 0; i < infos.length; i++) {
			try {
				device = MidiSystem.getMidiDevice(infos[i]);
				// open each device
				device.open();
				System.out.println("maxTransmitters: "+device.getMaxTransmitters());
				// does the device have any transmitters?
				// if it does, add it to the device list
				System.out.println(infos[i]);

				// get all transmitters
				List<Transmitter> transmitters = device.getTransmitters();
				// and for each transmitter

				for (int j = 0; j < transmitters.size(); j++) {
					// create a new receiver
					transmitters.get(j).setReceiver(parent);
				}
				if(transmitters.size()==0)
					System.out.println("no transmitters");
				else
					System.out.println("has transmitters");

				if (device instanceof Sequencer) {
					System.out.println("        Device is a sequencer");
				}
				if (device instanceof Synthesizer) {
					System.out.println("        Device is a synthesizer");
				}
				// if code gets this far without throwing an exception
				// print a success message
				System.out.println(device.getDeviceInfo() + " Was Opened");
				Transmitter trans = device.getTransmitter();
				trans.setReceiver(parent);

			} catch (MidiUnavailableException e) {
				e.printStackTrace();
			}
		}
	}

}
